import { defineStore } from 'pinia'

interface CartItem {
    id: number
    name: string
    price: number
    quantity: number
    description?: string
}

interface CartState {
    items: CartItem[]
}

export const useCartStore = defineStore('cart', {
    state: (): CartState => {
        return {
            items: []
        }
    },

    getters: {
        totalPrice: (state) => {
            return state.items.reduce((total, item) => {
                return total + (item.price * item.quantity)
            }, 0)
        },
        cartItemsCount: (state) => {
            return state.items.reduce((count, item) => count + item.quantity, 0)
        }
    },

    actions: {
        addToCart(product: { id: number; name: string; price: number; description?: string }) {
            const existingItem = this.items.find(item => item.id === product.id)

            if (existingItem) 
            {
                existingItem.quantity++
            } 
            else 
            {
                this.items.push({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    quantity: 1,
                    description: product.description
                })
            }
            
            console.log('购物车商品:', this.items)
        }
    }
})
